package com.chinairi.mall.controller;

import com.chinairi.common.controller.BaseController;
import com.chinairi.common.utils.ResponseUtil;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * <p>
 * 文件上传功能接口
 * </p>
 *
 * @author Webgasd
 * @since 2020-09-09
 */
@RestController
@RequestMapping("/upload")
public class FileController extends BaseController {

    /**
     * 实现图片上传功能
     * @param file 文件
     * @throws IOException 异常
     */
    @PostMapping("/uploadPicture")
    @ResponseBody
    public void pictureUpload(MultipartFile file) throws IOException {
        String name = uploadFile(file, "picture");
        ResponseUtil.showMessage("SUCCESS", "图片上传成功", name);
    }

    /**
     * 实现视频上传
     * @param file 文件
     * @throws IOException 异常
     */
    @PostMapping("/uploadVideo")
    @ResponseBody
    public void videoUpload(MultipartFile file) throws IOException {
        String name = uploadFile(file, "video");
        ResponseUtil.showMessage("SUCCESS", "视频上传成功", name);
    }

    /**
     * 实现文件上传
     * @param file 文件
     * @throws IOException 异常
     */
    @PostMapping("/uploadReport")
    @ResponseBody
    public void reportUpload(MultipartFile file) throws IOException {
        String name = uploadFile(file, "report");
        ResponseUtil.showMessage("SUCCESS", "文件上传成功", name);
    }

    /**
     * 上传接口子功能
     * @param file 文件名
     * @param type 上传类型
     * @return String 文件类型/时间戳文件夹名称/时间戳文件名称
     * @throws IOException 异常
     */
    public String uploadFile(MultipartFile file, String type) throws IOException {
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String currentTime = dateFormat.format(now);

        String fileName = file.getOriginalFilename();
        System.out.println("源文件名：" + fileName);
        File filed = new File("upload/" + type + "/" + currentTime);
        if (!filed.exists()) {
            filed.mkdirs();
        }
        String filename = System.currentTimeMillis() + (int) (1 + Math.random() * 1000) + fileName.substring(fileName.lastIndexOf("."));
        file.transferTo(new File(filed.getAbsolutePath(), filename));
        System.out.println(type + "/" + currentTime + "/" + filename);
        return type + "/" + currentTime + "/" + filename;
    }

    /**
     * 实现文件下载（已弃用）
     * @param response 返回
     * @param fileName 请求文件名
     */
    @GetMapping("/downloadFile")
    public void downloadFile(HttpServletResponse response, String fileName) {
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(new File("upload/report", fileName)));
            //            bis = new BufferedInputStream(new FileInputStream(new File("upload/report",fileName)));
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 文件下载新方法（用这个下载）
     * @param response 返回
     * @param fileName 文件名，格式为后端返回的文件名即type/时间戳文件夹/时间戳文件名
     */
    @GetMapping("/downloadFileEx")
    public static void downloadFileEx(HttpServletResponse response, String fileName) {
        //下载
        File file = new File("upload/" + fileName);//   1.获取要下载的文件的绝对路径
//        File file = new File("upload/report/"+fileName);//   1.获取要下载的文件的绝对路径
//        File file = new File(fileName);//   1.获取要下载的文件的绝对路径
        System.out.println(fileName);
        if (file.exists()) {  //判断文件是否存在
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/xlsx");
            try {
                response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName
                        .getBytes(StandardCharsets.UTF_8), "ISO8859-1"));  //3.设置content-disposition响应头控制浏览器以下载的形式打开文件.特别注意，在swagger中会练吗，
                // 但是其实不会乱码。
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            byte[] buff = new byte[1024];    //5.创建数据缓冲区
            BufferedInputStream bis = null;
            OutputStream os = null;
            OutputStream outputStream = null;
            try {
                FileInputStream inputStream = new FileInputStream(file);
                outputStream = response.getOutputStream();
                IOUtils.copy(inputStream, outputStream);
                response.flushBuffer();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (outputStream != null) {
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {
            System.out.println("1");
        }
    }

}
